import $ from 'jquery'

var observer = new MutationObserver(function (mutations) {
    mutations.forEach(function (mutation) {
        if (mutation.type === 'childList' && mutation.addedNodes[0]) {
            if ($(mutation.addedNodes[0]).find(".ld-select").length !== 0) { // 监听元素的创建
                const inputs = mutation.addedNodes[0].querySelectorAll("select")
                // console.log(inputs);
                for (let i = 0; i < inputs.length; i++) {
                    let data = []
                    if (!$(inputs[i]).attr("placeholder")) {
                        $(inputs[i]).attr("label", $(inputs[i]).find("option").eq(0).attr("label"))
                        $(inputs[i]).val($(inputs[i]).find("option").eq(0).attr("value"))
                    }
                    $(inputs[i]).find("option").each(function () {
                        data.push({
                            label: $(this).attr("label"),
                            value: $(this).attr("value"),
                            disabled: $(this).attr("disabled") || ""
                        })
                    })
                    renderSelect($(inputs[i]), $(inputs[i]).val(), $(inputs[i]).attr("label"), $(inputs[i]).attr("placeholder"), $(inputs[i]).attr("width"), $(inputs[i]).attr("height"), $(inputs[i]).attr("disabled"), data)
                }
            }
        }
    });
});

observer.observe(window.document, {
    subtree: true,
    childList: true,
    attributes: true,
    attributeFilter: ['src', 'href', 'action']
});

$(".ld-select").each(function () {
    let el = $(this),
        value = $(this).attr("value"),
        label = $(this).attr("label"),
        placeholder = $(this).attr("placeholder"),
        width = $(this).attr("width") || '180px',
        height = $(this).attr("height") || '40px',
        disabled = $(this).attr("disabled"),
        data = []

    if (!placeholder) {
        label = $(this).find("option").eq(0).attr("label")
        value = $(this).find("option").eq(0).attr("value")
    }
    $(this).find("option").each(function () {
        data.push({
            label: $(this).attr("label"),
            value: $(this).attr("value"),
            disabled: $(this).attr("disabled") || ""
        })
    })
    renderSelect(el, value, label, placeholder, width, height, disabled, data)
})

function renderSelect(el, value, label, placeholder, width, height, disabled, data) {
    // console.log(el, value, label, placeholder, width, height, disabled);
    if (!value) value = ""
    if (!label) label = ""
    if (!placeholder) placeholder = ""
    if (disabled === undefined) disabled = ""
    // 动态ID
    const id = "ld-select-" + new Date().getTime()
    // 获取 class
    const className = el.attr("class").split("ld-select")[1]
    const str = `<div class="ld-select-item ${className}" ${disabled}>
                    <input init="${id}" placeholder="${placeholder}" disabled type="text" class="ld-select-inner" value="${label}" code="${value}" style="width: ${width};height:${height};">
                    <i class="iconfont icon-arrow-up"></i>
                </div>`
    el.before(str)
    el.remove()
    const hidddenStr = `<input type="hidden" value='${JSON.stringify(data)}' ld-select-hiddenId="${id}">`
    $("body").append(hidddenStr)
}

// 展开下拉选
$("body").on("click", ".ld-select-item", function (e) {
    if ($(this).attr("disabled") === "" || $(this).attr("disabled") === "disabled") return
    // 获取 高度
    const height = $(this).height()
    // 获取 宽度
    const width = $(this).width()
    // 获取 高度
    const offsetHeight = $(this).offset().top
    // 获取 宽度
    const offsetWidth = $(this).offset().left
    e.stopPropagation()
    $(".ld-select-dropdown").remove()
    $(this).toggleClass("is-select")


    // 请选择的显示
    let placeholder = $(this).find(".ld-select-inner").attr("placeholder")
    let placeholderStr = ""
    if (placeholder)
        placeholderStr = `<li code="" label="">请选择</li>`

    const id = $(this).find(".ld-select-inner").attr("init").split("ld-select-")[1]
    const data = JSON.parse($("input[ld-select-hiddenid=ld-select-" + id + "]").val())
    // 获取已选择的数据
    const selectValue = $(this).find(".ld-select-inner").attr("code")
    if ($(this).hasClass("is-select")) {
        $(".is-select").toggleClass("is-select")
        $(this).addClass("is-select")

        let option = ""
        let selected = ""
        // console.log(data);
        data.forEach(val => {
            if (val.value === selectValue)
                selected = "selected"
            else
                selected = ""

            option += `<li ${val.disabled} class="${selected}" code=${val.value} label=${val.label}>${val.label}</li>`
        })
        let str = `<div class="ld-select-dropdown" prop="${id}">
                        <ul>${placeholderStr}${option}</ul>
                        <div class="ld-select-dropdown-arr"></div>
                </div>`
        $("body").append(str)
        $(".ld-select-dropdown[prop=" + id + "]").css("top", (offsetHeight + height) + "px")
        $(".ld-select-dropdown[prop=" + id + "]").css("left", offsetWidth + "px").css("width", width + "px")
    } else {
        $(".ld-select-dropdown[prop=" + id + "]").remove()
    }
})

// 点击别的地方，移除下拉选
$("body").click(function (e) {
    $(".ld-select-dropdown").remove()
    $(".is-select").removeClass("is-select")
})

$("body").on("click", ".ld-select-dropdown li", function () {
    if ($(this).attr("disabled") === "disabled") return
    const data = {
        label: $(this).attr("label"),
        value: $(this).attr("code"),
    }
    const id = $(this).parents(".ld-select-dropdown").attr("prop")
    $(".ld-select-item input[init=ld-select-" + id + "]").val(data.label)
    $(".ld-select-item input[init=ld-select-" + id + "]").attr("code", data.value)
})
